﻿using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using ExpertMIS.Brokers;
using System.Collections;
using ExpertMIS.Entities;
using System.Data;
using SYS.Common.Broker;
using System.Configuration;

namespace ExpertMIS.Admin.UserControl
{
    public partial class ExpertRegisterTable : System.Web.UI.UserControl
    {
        private string _currentDomain = string.Empty;
        private DomainBroker _domainBroker = new DomainBroker();

        private void BindingCodes(string CodeName, bool AllowNull, DropDownList ddl)
        {
            DataTable dt = CodeManagerBroker.GetCodeManagerBroker().GetCodeDataByName(CodeName, AllowNull);

            ddl.DataValueField = "code";
            ddl.DataTextField = "name";
            ddl.DataSource = dt;

            ddl.DataBind();
            ddl.EnableViewState = true;
        }

        private void RefreshDomain()
        {
            if (dlDomains.DataSource == null)
            {
                IList<DomainEntity> list = _domainBroker.GetRootDomain();

                dlDomains.DataSource = list;
                dlDomains.DataBind();
            }
        }

        private void OnChildItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                CheckBox chkDomain = e.Item.FindControl("chkDomain") as CheckBox;
                DomainEntity childComain = e.Item.DataItem as DomainEntity;
                if (chkDomain != null)
                {
                    chkDomain.Attributes.Add("domain", childComain.OID);
                    chkDomain.Attributes.Add("parentdomain", _currentDomain);
                }
            }
        }

        private void GetCheckedChildDomain(DataList dlChild, ref List<string> list)
        {
            foreach (DataListItem item in dlChild.Items)
            {
                CheckBox chkDomain = item.FindControl("chkDomain") as CheckBox;
                if (chkDomain != null && chkDomain.Checked)
                {
                    list.Add(chkDomain.Attributes["domain"]);
                }
            }
        }

        private List<string> GetCheckedDomain()
        {
            List<string> listForReturn = new List<string>();

            foreach (DataListItem item in dlDomains.Items)
            {
                CheckBox chkDomainRoot = item.FindControl("chkDomainRoot") as CheckBox;
                if (chkDomainRoot != null && chkDomainRoot.Checked)
                {
                    listForReturn.Add(chkDomainRoot.Attributes["domain"]);
                }

                DataList dlChilds = item.FindControl("dlChilds") as DataList;
                if (dlChilds != null)
                {
                    GetCheckedChildDomain(dlChilds, ref listForReturn);
                }
            }

            return listForReturn;
        }

        private void SetChildDomainCheckStatus(DataList dlChilds, IList<ExpertBelongDomainEntity> list)
        {
            foreach (DataListItem item in dlChilds.Items)
            {
                CheckBox chkDomain = item.FindControl("chkDomain") as CheckBox;
                if (chkDomain != null)
                {
                    chkDomain.Checked = false;
                    foreach (ExpertBelongDomainEntity entity in list)
                    {
                        if (chkDomain.Attributes["domain"] == entity.DomainOID)
                        {
                            chkDomain.Checked = true;
                            break;
                        }
                    }
                }
            }
        }

        private void SetDomainCheckStatus(IList<ExpertBelongDomainEntity> list)
        {
            RefreshDomain();

            foreach (DataListItem item in dlDomains.Items)
            {
                CheckBox chkDomainRoot = item.FindControl("chkDomainRoot") as CheckBox;
                if (chkDomainRoot != null)
                {
                    chkDomainRoot.Checked = false;
                    foreach (ExpertBelongDomainEntity entity in list)
                    {
                        if(chkDomainRoot.Attributes["domain"] == entity.DomainOID)
                        {
                            chkDomainRoot.Checked = true;
                            break;
                        }
                    }
                }
                DataList dlChilds = item.FindControl("dlChilds") as DataList;
                SetChildDomainCheckStatus(dlChilds, list);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            txAwards.Wrap = true;
            txExpertise.Wrap = true;

            if (!IsPostBack)
            {
                BindingCodes("民族", true, ddlNational);
                BindingCodes("教育程度", true, ddlDegree);
                BindingCodes("籍贯", true, ddlOrigin);
                BindingCodes("政治面貌", true, ddlParties);
                RefreshDomain();
            }
        }

        protected void dlDomains_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                DataList dlChilds = e.Item.FindControl("dlChilds") as DataList;
                DomainEntity entity = e.Item.DataItem as DomainEntity;
                if (dlChilds != null && entity != null)
                {
                    _currentDomain = entity.OID;
                    dlChilds.ItemDataBound += new DataListItemEventHandler(OnChildItemDataBound);
                    dlChilds.DataSource = _domainBroker.GetChildDomain(entity.OID);
                    dlChilds.DataBind();
                }
            }
        }

        public ExpertEntity Entity
        {
            get
            {
                return ViewState["_" + GetType().ToString() + "_"] as ExpertEntity;
            }
            set
            {
                ViewState["_" + GetType().ToString() + "_"] = value;
            }
        }

        public void LoadExpert(string ExpertOID)
        {
            ExpertBroker broker = new ExpertBroker();

            Hashtable htQuery = new Hashtable();
            htQuery["OID"] = ExpertOID;
            Entity = broker.GetEntity(htQuery) as ExpertEntity;

            if (Entity == null)
            {
                Entity = broker.NewEntity() as ExpertEntity;
            }
            else
            {
                txName.Text = Entity.Name;
                txAdminPosition.Text = Entity.AdminPosition;
                txAwards.Text = Entity.Awards;
                txExpertise.Text = Entity.Expertise;
                txBornDate.Text = Entity.Birthday;
                txCellPhone.Text = Entity.CellPhone;
                txWhenJoinWork.Text = Entity.DateToJoinWork;
                txEMail.Text = Entity.EMail;
                txFixedPhone.Text = Entity.Phone;
                txSkills.Text = Entity.Skills;
                txSchoolMajor.Text = Entity.Major;
                
                ddlNational.SelectedValue = Entity.National;
                ddlOrigin.SelectedValue = Entity.Origin;
                ddlParties.SelectedValue = Entity.Parties;
                ddlDegree.SelectedValue = Entity.Degree;
                rbMale.Checked = (Entity.Gender == 1);
                rbFemale.Checked = (Entity.Gender == 2);

                ExpertBelongDomainBroker relatedBroker = new ExpertBelongDomainBroker();
                SetDomainCheckStatus(relatedBroker.GetDomainByExpertOID(Entity.OID));
            }

            // Modify, wdong, 2009-9-3, add default nopic
            if (string.IsNullOrEmpty(Entity.Graphic))
            {
                Entity.Graphic = "";
            }

            imgPhoto.ImageUrl = "~/Service/GetPhoto.aspx?w=128&h=128&filename=" + Entity.Graphic;
        }

        public bool SaveExpert()
        {
            try
            {
                ExpertBroker broker = new ExpertBroker();
                if (Entity == null)
                {
                    Entity = broker.NewEntity() as ExpertEntity;
                }

               
                Entity.Name = txName.Text;
                Entity.AdminPosition = txAdminPosition.Text;
                Entity.Awards = txAwards.Text;
                Entity.Expertise = txExpertise.Text;
                Entity.Birthday = txBornDate.Text;
                Entity.CellPhone = txCellPhone.Text;
                Entity.DateToJoinWork = txWhenJoinWork.Text;
                Entity.EMail = txEMail.Text;
                Entity.Phone = txFixedPhone.Text;
                Entity.Skills = txSkills.Text;
                Entity.Major = txSchoolMajor.Text;

                ///////////////////////////////////////////////////////////
                // Expert Photo
                if (fuPhoto.HasFile)
                {
                    string filename = Guid.NewGuid().ToString() + "." + System.IO.Path.GetExtension(fuPhoto.FileName);
                    string filepath = Server.MapPath(ConfigurationManager.AppSettings["UserUpload"]);
                    fuPhoto.SaveAs(filepath + filename);
                    Entity.Graphic = filename;
                }

                Entity.National = ddlNational.SelectedValue;
                Entity.Origin = ddlOrigin.SelectedValue;
                Entity.Parties = ddlParties.SelectedValue;
                Entity.Degree = ddlDegree.SelectedValue;
                Entity.Gender = rbMale.Checked ? 1 : 2;

                Hashtable htChilds = new Hashtable();
                htChilds.Add("domains", GetCheckedDomain());

                broker.SaveEntity(Entity, htChilds);
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}